package com.yunchao.bank.business.data.repository

import com.google.gson.Gson
import com.yunchao.bank.business.data.mapper.toDomainModel
import com.yunchao.bank.business.data.model.BusinessIssueInfoApiModel
import com.yunchao.feature.base.data.CacheManager
import com.yunchao.feature.base.domain.constants.LOOP_POWER_KEY
import com.yunchao.feature.base.domain.constants.SINGLE_POWER_KEY
import com.yunchao.bank.business.domain.model.BusinessInfoModel
import com.yunchao.bank.business.domain.model.BusinessPackModel
import com.yunchao.bank.business.domain.repository.BusinessRepository
import com.yunchao.bank.main.data.repository.DispatchTaskDatasource
import com.yunchao.library.lock.DeviceHelper
import com.yunchao.library.lock.IDeviceHelper.Companion.SINGLE_SCAN_POWER
import kotlinx.coroutines.flow.Flow

internal class BusinessRepositoryImpl(
    private val datasource: DispatchTaskDatasource,
    private val deviceHelper: DeviceHelper,
    private val gson: Gson
) : BusinessRepository {


    override suspend fun getBusinessInfo(taskId: Int): Result<BusinessInfoModel?> = runCatching {
        datasource.getTaskData(taskId)?.let {
            gson.fromJson(it.second, BusinessIssueInfoApiModel::class.java).toDomainModel(taskId)
        }
    }

    override suspend fun setupPower(isLoop: Boolean): Result<Boolean> = runCatching {
        val power = if (isLoop) CacheManager.getString(LOOP_POWER_KEY) else CacheManager.getString(
            SINGLE_POWER_KEY
        )
        deviceHelper.setPower(power = power?.toIntOrNull() ?: SINGLE_SCAN_POWER)
    }

    override suspend fun inventoryOnce(
        businessInfoModel: BusinessInfoModel,
        packInfoMap: Map<String, BusinessPackModel>
    ): Result<BusinessPackModel> {
        TODO("Not yet implemented")
    }

    override suspend fun inventoryLoop(
        businessInfoModel: BusinessInfoModel,
        packInfoMap: Map<String, BusinessPackModel>
    ): Flow<List<BusinessPackModel>> {
        TODO("Not yet implemented")
    }

    override suspend fun inventoryStop(
        businessInfoModel: BusinessInfoModel,
        payloads: List<BusinessPackModel>,
        isLoop: Boolean
    ) {
        TODO("Not yet implemented")
    }

    override suspend fun closeLockWriteLogistics(
        businessInfoModel: BusinessInfoModel,
        packInfo: BusinessPackModel,
        busiInfo: BusinessPackModel,
        pageNumber: Int
    ): Result<BusinessPackModel> {
        TODO("Not yet implemented")
    }

    override suspend fun openLockWriteLogistics(
        packInfoMap: Map<String, BusinessPackModel>,
        taskInfo: BusinessInfoModel
    ): Result<BusinessPackModel> {
        TODO("Not yet implemented")
    }

    override suspend fun submitBusiness(
        businessInfoModel: BusinessInfoModel,
        items: List<BusinessPackModel>
    ): Result<String> {
        TODO("Not yet implemented")
    }
}